package com.team.bus.module.organization.controller;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.team.bus.module.user.model.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.zjframework.traceframe.common.controller.BaseController;
import org.zjframework.traceframe.common.dao.util.ConfigUtil;
import org.zjframework.traceframe.common.dao.util.StringUtil;
import org.zjframework.traceframe.common.util.ContextHolderUtils;
import org.zjframework.traceframe.common.util.JSONUtil;
import org.zjframework.traceframe.common.util.PageHelper;
import com.team.bus.module.common.pagemodel.SessionInfo;
import com.team.bus.module.menu.model.Menu;
import com.team.bus.module.menu.service.IMenuService;
import com.team.bus.module.organization.model.Organization;
import com.team.bus.module.organization.pagemodel.Porganization;
import com.team.bus.module.organization.service.IOrganizationService;
    
@Controller
@RequestMapping("/oz")
public class OrganizationController extends BaseController {
	/**
	 * Logger for this class
	 */
	
	private IOrganizationService organizationService;
	
	@Autowired
	private IMenuService menuService;
	
	public IOrganizationService getOrganizationService() {
		return organizationService;
	}

	@Resource
	public void setOrganizationService(IOrganizationService organizationService) {
		this.organizationService = organizationService;
	}


	private Organization organization = new Organization();
	
	public Organization getOrganization() {
		return organization;
	}

	public void setOrganization(Organization organization) {
		this.organization = organization;
	}

	@RequestMapping("/oz4user")
	public String oz4user(HttpServletRequest request){
		
		String hql = "from Organization o where 1=1 and o.organization.id!=null";
		Map<String,Object> param = new HashMap<String,Object>();
		List<Organization> ozs = organizationService.findHql(hql, param);
		request.setAttribute("ozs", ozs);
		return "organization/visit4office";
	}  
	
	/**
	 * @author 赵继
	 * @return
	 * 功能描述：跳转到栏目页列表页
	 */
	@RequestMapping("/oz")
	public String show(){
		return "organization/oz";
	}   
	
	@RequestMapping(value = "/getOZTreeMenu")  
    public void getTreeMenu(String id,HttpServletRequest request,HttpServletResponse response) {
		List<Organization> ozs = new ArrayList<>();
		List<Porganization> pozs = new ArrayList<>();
		if(id==null || id.equals("")){
			ozs = organizationService.findHql("from Organization where organization is null order by (orderno+0)");
		}else{
			ozs = organizationService.findHql("from Organization where organization.id=? order by (orderno+0)",id);
		}
		for(Organization oz : ozs){
			Porganization poz = new Porganization();
			BeanUtils.copyProperties(oz, poz);
			Map<String,Object> attributes = new HashMap<>();
			attributes.put("url", oz.getUrl());
			poz.setAttributes(attributes);
			if(oz.getOrganizations()!=null && !oz.getOrganizations().isEmpty()){
				poz.setState("closed");
			}else{
				poz.setState("open");
			}
			pozs.add(poz);
		}
		super.writeJSON(pozs,request,response);
    } 
	
	
	/**
	 * @author 赵继
	 * @return
	 * 功能描述：异步加载TreeGrid
	 */
	@RequestMapping("/treegrid")
	public void treegrid(HttpServletRequest request,HttpServletResponse response,PageHelper ph,String id){
		User user = (User)request.getSession().getAttribute("user");
		String hql = "";
		Map<String,Object> param = new HashMap<>();
			hql = "from Organization   order by (orderno+0)";
//		param.put("id",user.getOrganization().getId());
//		param.put("pid",user.getOrganization().getId());
		List<Organization> soz = organizationService.findHql(hql, param);
		List<Porganization> tozs = new ArrayList<>();
		Map<String,Object> attributes = new HashMap<>();
		for(Organization s : soz){
			Porganization m = new Porganization();
			BeanUtils.copyProperties(s, m);
			
			if(s.getOrganization()!=null){
				m.setPid(s.getOrganization().getId());
			}
			if(s.getUrl()!=null){
				attributes.put("url", s.getUrl());
			}
			if(StringUtil.isNotEmpty(s.getOrderno())){
				attributes.put("orderno", s.getOrderno());
			}
            if(StringUtil.isNotEmpty(s.getCode())){
                attributes.put("code", s.getCode());
            }
			m.setAttributes(attributes);
			tozs.add(m);
		}
		super.writeJSON(tozs, request, response);
	}
	
	
	@RequestMapping("/tree")
	@ResponseBody
	public List<Porganization> tree() {
		String hql = "";
		Map<String,Object> param = new HashMap<>();

		User user = (User) ContextHolderUtils.getSession().getAttribute("user");
		List<Organization> ozs = new ArrayList<>();
		if( !(user.getUsername().equals("aac")) ){
			param.put("pid", user.getOrganization().getId());
			hql = "from Organization where pid=:pid or id=:pid order by (orderno+0)";
			ozs = organizationService.findHql(hql, param);
		}else if(user.getUsername().equals("aac")){
			hql = "from Organization order by (orderno+0)";
			ozs = organizationService.findHql(hql, param);
		}
		List<Porganization> tozs = new ArrayList<>();
		Map<String,Object> attributes = new HashMap<>();
		for(Organization s : ozs){
			Porganization t = new Porganization();
			BeanUtils.copyProperties(s, t);
			
			if(s.getOrganization()!=null){
				t.setPid(s.getOrganization().getId());
			}
			if(s.getUrl()!=null){
				attributes.put("url", s.getUrl());
			}
			if(StringUtil.isNotEmpty(s.getOrderno())){
				attributes.put("orderno", s.getOrderno());
			}
            if(StringUtil.isNotEmpty(s.getCode())){
                attributes.put("code", s.getCode());
            }
			t.setAttributes(attributes);
			tozs.add(t);
		}
		return tozs;
	}

    /**
     * 获取指定级别的组织机构
     * @param leavel
     * @return
     */
    @RequestMapping("/tree1")
    @ResponseBody
    public List<Porganization> tree1(String leavel) {
        String hql = "";
        Map<String,Object> param = new HashMap<>();
        param.put("leavel",leavel);
        List<Organization> ozs = new ArrayList<>();
        hql = "from Organization where updatedatetime=:leavel order by (orderno+0)";
        ozs = organizationService.findHql(hql, param);
        List<Porganization> tozs = new ArrayList<>();
        Map<String,Object> attributes = new HashMap<>();
        for(Organization s : ozs){
            Porganization t = new Porganization();
            BeanUtils.copyProperties(s, t);

            if(s.getOrganization()!=null){
                t.setPid(s.getOrganization().getId());
            }
            if(s.getUrl()!=null){
                attributes.put("url", s.getUrl());
            }
            if(StringUtil.isNotEmpty(s.getOrderno())){
                attributes.put("orderno", s.getOrderno());
            }
            if(StringUtil.isNotEmpty(s.getCode())){
                attributes.put("code", s.getCode());
            }
            t.setAttributes(attributes);
            tozs.add(t);
        }
        return tozs;
    }
	
	
	/**
	 * @author 赵继
	 */   
	@RequestMapping("/addTo")
	public String addTo(){
		   
		return "/organization/ozAdd";
	}
	
	
	/**
	 * @author 赵继
	 */   
	@RequestMapping("/editTo")
	public String editTo(){
		   
		return "/organization/ozEdit";
	}
	
	/**
	 * @author 赵继
	 */   
	@RequestMapping("/edit")
	public void edit(HttpServletRequest request,HttpServletResponse response,Porganization poz){
		JSONUtil json = new JSONUtil();
		Organization oz = new Organization();
			try {    
				if(poz!=null){
					BeanUtils.copyProperties(poz, oz);
                    if(poz.getCode().length()==4){
                        oz.setUpdatedatetime("3");
                    }else if(poz.getCode().length()==8){
                        oz.setUpdatedatetime("4");
                    }
                    oz.setValue(poz.getCode());
					Organization oz1 = new Organization();
					if(!StringUtil.isEmpty(poz.getPid())){
						 oz1 = organizationService.get(Organization.class, poz.getPid());
						 oz.setOrganization(oz1);
					}
					oz = organizationService.updateRow(oz);
					json.setSuccess(true);
					json.setMsg("编辑成功");
					poz.setId(poz.getId());
					if(StringUtil.isNotEmpty(oz.getOrganization())){
						poz.setPid(oz.getOrganization().getId());
					}
					json.setObj(poz);
				}
			} catch (Exception e) {
				e.printStackTrace();
				json.setMsg(e.getMessage());
			}
		super.writeJSON(json,request,response);
	}
	
	
	/**
	 * @author 赵继
	 */   
	@RequestMapping("/save")
	public void save(HttpServletRequest request,HttpServletResponse response,
			Porganization poz){
		   
		JSONUtil json = new JSONUtil();
		Organization oz = new Organization();
			try {    
				if(poz!=null){
					BeanUtils.copyProperties(poz, oz);
                    if(poz.getCode().length()==4){
                        oz.setUpdatedatetime("3");
                    }else if(poz.getCode().length()==8){
                        oz.setUpdatedatetime("4");
                    }
                    oz.setValue(poz.getCode());
                    if(!StringUtil.isEmpty(poz.getPid())){
                        Organization oz1 = organizationService.get(Organization.class, poz.getPid());
                        oz.setOrganization(oz1);
                    }
					oz = organizationService.saveInsertRow(oz);
					json.setSuccess(true);
					json.setMsg("操作成功");
					poz.setId(oz.getId());
					if(StringUtil.isNotEmpty(oz.getOrganization())){
						poz.setPid(oz.getOrganization().getId());
					}
					json.setObj(poz);
				}
			} catch (Exception e) {
				e.printStackTrace();
				json.setMsg(e.getMessage());
			}
		super.writeJSON(json,request,response);
	}
	
	/**
	 * @author 赵继
	 */
	@RequestMapping("/del")
	public void delete(HttpServletRequest request,HttpServletResponse response,String ids){
		
		JSONUtil json = new JSONUtil();
		StringBuffer hql = new StringBuffer();
		hql.append("delete Organization where id=");
		hql.append("'"+ids+"'");
		try {
			organizationService.executeHql(hql.toString());
			json.setSuccess(true);
			json.setMsg("删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			json.setMsg("删除失败:"+e.getMessage());
		}
		super.writeJSON(json,request,response);
	}
	
	
	/**
	 * @author 赵继
	 * 转向角色列表页
	 */   
	@RequestMapping("/menuTreePage")
	public String menuTreePage(HttpServletRequest request,HttpServletResponse response,String id){
		Organization oz = organizationService.get(Organization.class, id);
		request.setAttribute("oz", oz);
		return "/organization/ozTree";
	}
	
	
	/**
	 * @author 赵继
	 * 给用户设定角色
	 */
	@RequestMapping("/grantMenu4oz")
	public void grantMenu(HttpServletRequest request,HttpServletResponse response,Porganization poz,String menuIds){
		   
		JSONUtil json = new JSONUtil();
			try {    
				if(poz!=null){
					BeanUtils.copyProperties(poz, this.organization);
					Set<Menu> menuSet = new HashSet<Menu>();
					for (String menuId : menuIds.split(",")) {
						if (!StringUtils.isBlank(menuId)) {
							Menu menu = menuService.get(Menu.class, menuId);
							if (menu != null) {
								menuSet.add(menu);
							}
						}
					}
					organization.setMenus(menuSet);
					organizationService.updateRow(organization);
					json.setSuccess(true);
					json.setMsg("用户授权成功");
				}
			} catch (Exception e) {
				e.printStackTrace();
				json.setMsg("用户授权失败  原因："+e.getMessage());
			}
		super.writeJSON(json,request,response);
	}
	
}
